package com.juc.demo1;
import	java.util.concurrent.locks.ReentrantLock;

import java.util.concurrent.locks.Lock;

public class SaleTicketDemo02 {
    public static void main(String[] args) {
        //并发，多线程操作一个资源类，把资源类丢入线程
        Ticket2 ticket = new Ticket2();
        new Thread(()->{ for (int i = 1; i < 40; i++)ticket.sale(); },"A").start();
        new Thread(()->{ for (int i = 1; i < 40; i++)ticket.sale(); },"B").start();
        new Thread(()->{ for (int i = 1; i < 40; i++)ticket.sale(); },"C").start();
    }
}

//资源类oop编程
class Ticket2{
    private  int number = 50;
    Lock lock = new ReentrantLock();
    public void sale() {
        lock.lock();    //加锁
        try {
            //业务模块
            if(number>0){
                System.out.println(Thread.currentThread().getName() +"卖出了"+(number--)+"票,还剩"+number+"张");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
